# coding:utf-8

import os

import shutil

from pywpsrpc.rpcetapi import createEtRpcInstance, etapi
from pywpsrpc.common import S_OK


FORMAT_DICT = {
    'xls': etapi.xlExcel8,
    'xlsx': etapi.xlWorkbookDefault,
}


def file2xls(request_property):
    result, rpc_excel = createEtRpcInstance()

    if result != S_OK:
        raise Exception('create the rpc instance is failed', result)
    result, app_excel = rpc_excel.getEtApplication()
    try:
        app_excel.Visible = False
        workbooks = app_excel.Workbooks
        file_path = request_property['input_path']
        file_format = request_property['file_format']
        result, workbook = workbooks.Open(file_path)
        base_path, file_ext = file_path.rsplit('.')
        new_file = f'{base_path}_tmp.{file_format}'
        if os.path.exists(new_file):
            os.remove(new_file)
        workbook.SaveAs(Filename=new_file, FileFormat=FORMAT_DICT[file_format])
        workbook.Close()
        # shutil.move(new_file, file_path)
    finally:
        app_excel.Quit()


aaa = {
    'file_format': 'xlsx',
    'input_path': '/home/mjtree/文档/html.xls'

}
file2xls(aaa)
